# coding=utf-8
import time
from typing import Dict, Optional

from obespoir.share.singleton import Singleton

CACHE_SYNC_INTERVAL = 1800  # 60s


class User(object):

    def __init__(self):
        self.user_id: str = ""
        self.session_id: str = ""
        self.extra: Dict = {}

    def to_dict(self) -> Dict:
        return {
            "user_id": self.user_id,
            "session_id": self.session_id,
            "extra": self.extra
        }


class UserManager(object, metaclass=Singleton):

    def __init__(self):
        super().__init__()

        # user_id: User
        self._user_info: Dict[str, User] = {}

        # session_id: user_id
        self._session_info: Dict[str, str] = {}

    def get_user(self, user_id: str) -> User:
        user = self._user_info.get(user_id)
        if not user:
            user = User()
            user.user_id = user_id
            self._user_info[user_id] = user
        return user

    def get_user_by_session(self, session_id: str) -> Optional[User]:
        user_id = self._session_info.get(session_id)
        if not user_id:
            return None
        return self.get_user(user_id)

    def update_session(self, session_id: str, user_id: str) -> None:
        self._session_info[session_id] = user_id
        user = self.get_user(user_id)
        if user.session_id in self._session_info:
            del self._session_info[user.session_id]

        user.session_id = session_id
        user.last_sync_time = int(time.time())

    def remove_user(self, user_id: str) -> None:
        user = self._user_info.get(user_id)
        if not user:
            return
        if user.session_id in self._session_info:
            del self._session_info[user.session_id]
        del self._user_info[user_id]
